package com.phonetools.commonutils.android.hardware

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.util.Log

const val REQUEST_ENABLE_BT = 12321

fun Activity.enableBluetoothAdapter() {
    val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
    bluetoothAdapter ?: return
    if (!bluetoothAdapter.isEnabled) {
        val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT)
    }
}

fun unPairDevice(device: BluetoothDevice): Boolean {
    return try {
        val m = device.javaClass.getMethod("removeBond")
        m.isAccessible = true
        m.invoke(device)
        true
    } catch (e: Exception) {
        Log.e("BluetoothUtils", e.message ?: "unPairDevice failed!")
        false
    }
}

fun adapterStateToString(state: Int) = when (state) {
    BluetoothAdapter.STATE_OFF -> {
        "Off"
    }
    BluetoothAdapter.STATE_ON -> {
        "On"
    }
    BluetoothAdapter.STATE_TURNING_OFF -> {
        "Turning Off"
    }
    BluetoothAdapter.STATE_TURNING_ON -> {
        "Turning On"
    }
    else -> {
        ""
    }
}

fun scanModeToString(adapterScanMode: Int) =
    when (adapterScanMode) {
        BluetoothAdapter.SCAN_MODE_NONE -> {
            "None"
        }
        BluetoothAdapter.SCAN_MODE_CONNECTABLE -> {
            "CONNECTABLE"
        }
        BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE -> {
            "CONNECTABLE\nDISCOVERABLE"
        }
        else -> {
            ""
        }
    }
